import os
import sys
from typing import Optional

from loguru import logger

from mdtool.publish.wx_htmler import WxHtmler
from mdtool.wx_cache import WxCache
from mdtool.wx_client import WxClient

from ..config_reader import Config
from ..error_handler import ErrorHandler
from ..image_processor import ImageProcessor
from ..markdown_document import MarkdownDocument

TMPL_DIR = "mdtool.assets"


class WxPublisher:
    """WeChat article publisher class."""

    def __init__(self, wx_cache: WxCache, config):
        """Initialize the WxPublisher.

        Args:
            mdtool.cache: WxCache instance for image caching, creates a new one if None
            config: Config object for credentials
        """
        if config is None:
            raise
        self.client = WxClient(config)
        default_tmpl_dir = os.path.join(sys.path[0], TMPL_DIR)
        html_template_dir = config.get(Config.TEMPLATEDIR, default_tmpl_dir)
        self.htmler = WxHtmler(html_template_dir)
        self.cache = wx_cache
        self.image_processor = ImageProcessor(self.client, self.cache, config)
        self.error_handler = ErrorHandler()

    def publish_single_article(self, md_doc: MarkdownDocument) -> Optional[str]:
        if len(md_doc.check_format()) > 0:
            logger.error("文章格式错误，无法发布")
            return None
        if not self.image_processor.process_article_images(md_doc):
            logger.error("文章图片上传失败，无法发布")
            return None
        article = self.htmler.generate_article(md_doc)
        media_id = self.client.upload_article_draft([article])
        if media_id:
            logger.info(f"文章 {md_doc.abs_path} 发布成功")
            self.cache.update(md_doc.get_full_path(), media_id)
            return media_id
        else:
            logger.error(f"文章 {md_doc.abs_path} 没有上传成功，发布失败.")
            return None
